package com.link510.aitools.services;

import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Point;
import android.view.Gravity;
import android.view.Window;
import android.view.WindowManager;

import com.google.common.base.Strings;
import com.link510.aitools.R;


public class CustomWaitDialogUtils {


    private ProgressDialog waitingDialog;

    private boolean isShow = false;

    public CustomWaitDialogUtils(Context context) {
        /*
     等待Dialog具有屏蔽其他控件的交互能力
         *
     @setCancelable 为使屏幕不可点击，设置为不可取消(false)
         *
     下载等事件完成后，主动调用函数关闭该Dialog
     */
        waitingDialog = new ProgressDialog(context, ProgressDialog.THEME_HOLO_DARK);
        waitingDialog.setMessage(context.getString(R.string.waiting));
        waitingDialog.setIndeterminate(true);
        waitingDialog.setCancelable(false);

    }

    /**
     * 是否显示
     *
     * @return
     */
    public boolean isShow() {
        return isShow;
    }

    public void show() {

        show("");
    }

    public void show(String message) {
        show(message, false);
    }


    public void show(String message, boolean isCancelable) {

        try {

            isShow = true;

            if (!Strings.isNullOrEmpty(message)) {
                waitingDialog.setMessage(message);
            }

            waitingDialog.setCancelable(isCancelable);
            waitingDialog.show();
            Point size = new Point();

            Window window = waitingDialog.getWindow();

            if (window != null) {

                window.getWindowManager().getDefaultDisplay().getSize(size);//记得用mProgressDialog来得到这个界面的大小，实

                int width = size.x;//获取界面的宽度像素
                int height = size.y;
                WindowManager.LayoutParams params = waitingDialog.getWindow().getAttributes();//一定要用mProgressDialog得到当前界面的参数对象，否则就不是设置ProgressDialog的界面了
                params.alpha = 0.8f;//设置进度条背景透明度
                params.height = height / 6;//设置进度条的高度
                params.gravity = Gravity.CENTER;//设置ProgressDialog的重心
                params.width = 9 * width / 10;//设置进度条的宽度
                params.dimAmount = 0.8f;//设置半透明背景的灰度，范围0~1，系统默认值是0.5，1表示背景完全是黑色的,0表示背景不变暗，和原来的灰度一样
                waitingDialog.getWindow().setAttributes(params);//把参数设置给进度条
            }
        } catch (Exception ex) {
            //ex.printStackTrace();
        }

    }

    public void setMessage(String message) {
        waitingDialog.setMessage(message);

    }

    public void close() {
        if (waitingDialog.isShowing()) {
            waitingDialog.cancel();
            isShow = false;
        }
    }

    public void cancel() {
        close();
    }

    public void dismiss() {
        waitingDialog.dismiss();
        isShow = false;
    }

}
